package com.cskaoyan.order.rocketmqconfig;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ProcessException;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.UnsupportedEncodingException;
import java.util.List;


/**
 * @ClassName RocketMqProducerAutoConfiguration
 * @Description TODO
 * @Author XiaoWJ
 * @Date 2022/9/22 14:16
 **/
@Slf4j
@Configuration
@EnableConfigurationProperties(value = {OrderDelayCancelProducerProperties.class, OrderDelayCancelConsumerProperties.class})
public class OrderDelayCancelProducerAutoConfiguration {

    @Autowired
    OrderDelayCancelProducerProperties properties;

    @Autowired
    OrderDelayCancelConsumerProperties consumerProperties;

    @Autowired
    OrderCoreService orderCoreService;

    @Bean
    public DefaultMQPushConsumer defaultMQPushConsumer() {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(consumerProperties.getConsumerId());

        consumer.setNamesrvAddr(consumerProperties.getNameServerAddr());

        consumer.setMessageListener((MessageListenerConcurrently) (msgList, consumeConcurrentlyContext) -> {
            // 取出消息
            MessageExt msg = msgList.get(0);
            byte[] body = msg.getBody();


            String orderId = null;
            try {
                orderId = new String(body, 0, body.length, consumerProperties.getCharset());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            // 调用取消订单的业务
            try {
                cancelOrderByStatus(orderId);
            }catch (Exception e) {
                log.info("订单:" + orderId + "超时自动取消业务异常");
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;

        });

        try {
            consumer.subscribe(consumerProperties.getSubFirst(), consumerProperties.getSubSecond());
            consumer.start();

            log.info("消息消费者开始监听消息");

        } catch (MQClientException e) {
            e.printStackTrace();
        }

        return consumer;


    }


    @Bean
    public DefaultMQProducer defaultMQProducer() {
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer(properties.getMsgProducerId());

        defaultMQProducer.setNamesrvAddr(properties.getNameServerAddr());

        //defaultMQProducer.setCreateTopicKey("AUTO_CREATE_TOPIC_KEY");

        try {
            defaultMQProducer.start();
            log.info("消息生产者开启服务");
        } catch (Exception e) {
            log.info("消息生产者开启服务失败");
            throw new ProcessException(SysRetCodeConstants.BAD_MSG_START.getCode()
                    , SysRetCodeConstants.BAD_MSG_START.getMessage());

        }

        return defaultMQProducer;
    }

    private void cancelOrderByStatus(String orderId) {

        boolean b = orderCoreService.cancelOrderByStatus(orderId);
        if (b) {
            log.info("订单：" + orderId + "超时未支付被自动取消");
        }
    }


}
